<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body" v-show="cartList.length">
        <ul class="cart-list" v-for="good in cartList" :key="good.id">
          <li class="cart-list-con1">
            <input
              type="checkbox"
              name="chk_list"
              :checked="good.isChecked"
              @change="changeChecked(good, $event)"
            />
          </li>
          <li class="cart-list-con2">
            <img :src="good.imgUrl" />
            <div class="item-msg">
              {{ good.skuName }}
            </div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ good.skuPrice }}.00</span>
          </li>
          <li class="cart-list-con5">
            <a
              href="javascript:void(0)"
              class="mins"
              @click="changeSkuNum('sub', good)"
              >-</a
            >
            <input
              autocomplete="off"
              type="text"
              :value="good.skuNum"
              minnum="1"
              class="itxt"
              @change="changeSkuNum('input', good, $event)"
            />
            <a
              href="javascript:void(0)"
              class="plus"
              @click="changeSkuNum('add', good)"
              >+</a
            >
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ good.cartPrice }}</span>
          </li>
          <li class="cart-list-con7">
            <a
              href="javascript:;"
              class="sindelet"
              @click="deleteOne(good.skuId)"
              >删除</a
            >
            <br />
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool" v-show="cartList.length">
      <div class="select-all">
        <input
          class="chooseAll"
          type="checkbox"
          :checked="isAll"
          @change="checkAll"
        />
        <span>全选</span>
      </div>
      <div class="option">
        <a href="javascript:;" @click="batchDeleteCart">删除选中的商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">
          已选择 <span>{{ totalNum }}</span
          >件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ totalPrice }}</i>
        </div>
        <div class="sumbtn">
          <router-link class="sum-btn" to="/trade">结算</router-link>
        </div>
      </div>
    </div>
    <div class="empty" v-show="!cartList.length">
      <img src="http://49.232.112.44/images/empty.gif" />
      <h2>购物车空空如也~~~</h2>
    </div>
  </div>
</template>

<script>
import {
  reqCartList,
  reqCheckCart,
  reqBatchCheckCart,
  reqDeleteCart,
  reqBatchDeleteCart
} from '@/api/cart'
import { reqAddCart } from '@/api/goodsDetail'
export default {
  name: 'ShopCart',
  data() {
    return {
      cartList: [],
      goodsSum: sessionStorage.getItem('goodsSum') * 1,
      goodsPriceNum: sessionStorage.getItem('goodsPriceNum') * 1,
      goodsCheck: sessionStorage.getItem('goodsCheck') * 1
    }
  },
  methods: {
    async getReqCartList() {
      const res = await reqCartList()
      // console.log(res)
      this.cartList = res.data
    },
    // 改变商品选中状态
    async changeChecked(good, e) {
      const id = good.skuId
      // 判断选中按钮是否是选中状态，如果是就返回1，如果不是就返回0
      const ischecked = e.target.checked ? 1 : 0
      // console.log(e.target.checked)
      // 点击选中框，首先需要向服务器更新最新的选中状态
      const res = await reqCheckCart(id, ischecked)
      // console.log(res)
      if (res.code === 200) {
        // 确定服务器的数据更新后，本地的也更新即可
        good.isChecked = ischecked
        // 把最新的商品选中状态存储到session
        this.goodsCheck = sessionStorage.setItem('goodsCheck', ischecked)
      }
    },
    // 全选按钮
    async checkAll(e) {
      // console.log(this.cartList)
      // 获取商品全选状态
      let { checked } = e.target
      // 将状态映射为0、1
      checked = checked ? 1 : 0

      // 声明一个空数组存储所有商品的skuId
      let skuid = []
      skuid = this.cartList.map((item) => item.skuId)
      // 向服务器发送请求
      const res = await reqBatchCheckCart(checked, skuid)
      // console.log(res)
      if (res.code === 200) {
        // 更改本地数据
        this.cartList.forEach((item) => (item.isChecked = checked))
      }
    },
    // 删除单个商品
    async deleteOne(id) {
      this.$confirm('确定删除所选商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await reqDeleteCart(id)
          if (res.code === 200) {
            this.cartList = this.cartList.filter((item) => item.skuId !== id)
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 删除多个商品
    async batchDeleteCart() {
      if (confirm('确认删除多个商品吗？')) {
        // 定义一个空数组用于存储选中的商品id
        const skuId = []
        // 遍历商品，筛选出选中的商品并把id存储到数组中
        this.cartList.forEach((item) => {
          if (item.isChecked === 1) {
            skuId.push(item.skuId)
          }
        })
        // 把数组通过接口返回给服务器
        const res = await reqBatchDeleteCart(skuId)
        // 当服务器接口调用成功后，在本地数组中删除所选中的商品
        if (res.code === 200) {
          this.cartList = this.cartList.filter(
            (item) => !skuId.includes(item.skuId)
          )
        }
      }
    },
    // 用户改变购物车商品数量
    async changeSkuNum(type, good, e) {
      // 获取当前操作商品的：skuId（编号）、skuNum（数量）
      const { skuId, skuNum } = good
      switch (type) {
        case 'add':
          if (skuNum > 200) return
          // eslint-disable-next-line
          const res1 = await reqAddCart(skuId, 1)
          if (res1.code === 200) {
            good.skuNum += 1
            good.isChecked = 1
          }
          break
        case 'sub':
          if (skuNum === 1) return
          // eslint-disable-next-line
          const res2 = await reqAddCart(skuId, -1)
          if (res2.code === 200) {
            good.skuNum -= 1
            good.isChecked = 1
          }
          break
        case 'input':
          // 获取用户输入的值
          // eslint-disable-next-line
          const { value } = e.target
          // eslint-disable-next-line
          const reg = /^([1-9]|[1-9]\d|1\d{2}|200)$/
          // 验证用户输入的值是否合法
          // eslint-disable-next-line
          const resReg = reg.test(value)
          // 用户输入的值合法，发送请求
          if (resReg) {
            const diff = skuNum - value
            const res = await reqAddCart(skuId, diff)
            // 请求成功，更改本地数据
            if (res.code === 200) {
              // console.log(res)
              good.skuNum = value * 1
              // 如果请求失败，就把skuNum改成之前的值
              // 注意用户输入的也需要更改
              good.isChecked = 1
            } else {
              good.skuNum = e.target.value = skuNum
            }
            // 用户输入的值大于200，按200的差值发送请求
          } else if (value > 200) {
            const diff = 200 - skuNum
            const res = await reqAddCart(skuId, diff)
            // 请求成功，更改本地数据
            if (res.code === 200) {
              // console.log(res)
              // data 中的数据本来就是 200，现在再次改为 200，页面不会重新渲染
              // 所以页面残留数据，加上e.target.value
              good.skuNum = e.target.value = 200
              good.isChecked = 1
            } else {
              good.skuNum = e.target.value = skuNum
            }
          }
          break

        default:
          break
      }
    }
  },
  mounted() {
    this.getReqCartList()
  },
  computed: {
    // 配置 判断商品是否全选
    isAll() {
      return this.cartList.every((item) => item.isChecked === 1)
    },
    // 已选商品总数
    totalNum() {
      let n = 0 // 初识化一个值，用于累加总数
      this.cartList.forEach((item) => {
        if (item.isChecked === 1) {
          n += item.skuNum
        }
      })
      return n
    },
    // 已选商品总金额
    totalPrice() {
      let Num = 0
      this.cartList.forEach((item) => {
        if (item.isChecked === 1) {
          // console.log(item.cartPrice)
          Num += item.cartPrice * item.skuNum
        }
      })
      return Num
    }
  }
}
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 15%;
        }
        .cart-list-con2 {
          width: 35%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }
        .cart-list-con4 {
          width: 10%;
        }
        .cart-list-con5 {
          width: 17%;
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
            text-decoration: none;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 31px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
            text-decoration: none;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;
        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: 'Microsoft YaHei';
          background: #e1251b;
          overflow: hidden;
          text-decoration: none;
          &hover {
            color: white !important;
          }
        }
      }
    }
  }
}
.empty {
  text-align: center;
  h2 {
    text-align: center;
    height: 100px;
    line-height: 100px;
  }
  img {
    width: 200px;
  }
}
</style>
